package com.shengqiang.cloud.oauth2.repository;

import com.shengqiang.cloud.oauth2.model.ProtectResource;
import com.shengqiang.cloud.oauth2.utils.RedisTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Administrator on 2017/12/11.
 * 管理资源Dao
 */
@Repository
public class OAuth2ResourceDao {

    private static final Logger logger = LoggerFactory.getLogger(OAuth2ResourceDao.class);

    private final String appHashKey = "h:oauth2:appResource";

    @Autowired
    private RedisTool<ProtectResource> redisTool;

    /**
     * 保持app资源信息
     *
     * @param resource
     * @return
     */
    public boolean saveAppResource(ProtectResource resource) {
        boolean flag = false;
        try {
            String valueKey = redisTool.generatorAppResourceKey(resource.getResourceId());
            flag = redisTool.saveOpsHash(appHashKey, valueKey, resource);
        } catch (Exception ex) {
            logger.error("注册APP资源信息出现异常异常:{}", ex.getMessage(), ex);
        }
        return flag;
    }

    /**
     * 查询指定Id的app资源信息
     *
     * @param resourceId
     * @return
     */
    public ProtectResource getProtectResource(String resourceId) {
        try {
            String valueKey = redisTool.generatorAppResourceKey(resourceId);
            ProtectResource resource = redisTool.queryOpsHash(appHashKey, valueKey, ProtectResource.class);
            return resource;
        } catch (Exception ex) {
            logger.error("查询指定的app资源信息出现异常:{}", ex.getMessage(), ex);
        }
        return null;
    }

    /**
     * 删除指定的资源信息
     *
     * @param resourceId
     * @return
     */
    public boolean deleteProtectResource(String resourceId) {
        boolean flag = false;
        try {
            String valueKey = redisTool.generatorAppResourceKey(resourceId);
            flag = redisTool.deleteOpsHash(appHashKey, valueKey);
        } catch (Exception ex) {
            logger.error("删除指定的资源信息：{}", ex.getMessage(), ex);
        }

        return flag;
    }

    /**
     * 查询资源信息列表
     *
     * @return
     */
    public List<ProtectResource> queryProtectResources() {
        try {
            List<ProtectResource> protectResources = redisTool.queryOpsHashList(appHashKey, ProtectResource.class);
            return protectResources;
        } catch (Exception ex) {
            logger.error("查询受保护资源的资源列表:{}", ex.getMessage(), ex);
        }
        return null;
    }
}
